package com.test.dababy.dababy_04_home;

import static com.test.dababy.dababy_00_utils.DababyConfigs.PermissionCode_Camera;
import static com.test.dababy.dababy_00_utils.DababyConfigs.PermissionCode_Home;
import static com.test.dababy.dababy_05_process.widget.OcrVie_dababywMana_dababyger.Flag_StartCam_dababyera;
import static com.test.dababy.dababy_00_utils.DababyUtil.startLoading;
import static com.test.dababy.dababy_00_utils.DababyUtil.stopLoading;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;

import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.PickVisualMediaRequest;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.test.dababy.Othe_dababyrsInfo;
import com.test.dababy.R;
import com.test.dababy.dababy_00_analytics.DababyUtil.DababyAnalyticsUtil;
import com.test.dababy.dababy_00_customer_service.Customer_dababyServiceDialog;
import com.test.dababy.dababy_00_customer_service.Feed_dababybackActivity;
import com.test.dababy.dababy_00_utils.DababyConfigs;
import com.test.dababy.dababy_00_utils.DababyUtil;
import com.test.dababy.dababy_00_utils.Photo_dababySelector_dababyDialog;
import com.test.dababy.dababy_00_utils.image_dababy.Image_dababyConvert;
import com.test.dababy.dababy_01_launcher.Base_dababyApplication;
import com.test.dababy.dababy_05_process.Pro_dababycessAct_dababyivity;
import com.test.dababy.dababy_05_process.Pro_dababycessIn_dababyfo;
import com.test.dababy.dababy_05_process.widget.OcrVie_dababywMana_dababyger;
import com.test.dababy.dababy_10_vip.VipInfoActivity_dababy;
import com.test.dababy.dababy_09_setting.Setti_dababyngActivi_dababyty;
import com.test.dababy.dababy_01_launcher.App_dababyShow_dababyCustomize;
import com.test.dababy.dababy_10_vip.Pers_dababyonalIn_dababyfo;
import com.test.dababy.dababy_00_http.OkHttpUtil;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import pub.devrel.easypermissions.EasyPermissions;

public class PersonalCenterF_dababyragment extends Fragment{


    private String ghaejrhgwe ="";
    private char hlikrj3 ='4';
    private double ghsrtjh2r =0.9819073579725874;
    private double gake2 =0.8989391823404798;
    private boolean jslror1 =false;
    private int hakje =298;
    private String hkje2 ="";
    private String kottto4 ="";
    public void hlakje(){
        new Thread(() -> {
            try {
                if (TextUtils.isEmpty(getGhaejrhgwe()))
                    setHkje2(String.valueOf(getHlikrj3())+ getGhsrtjh2r()+ getGake2()+ isJslror1());
                else setKottto4(String.valueOf(getHakje()));
            }catch (Exception e){
                e.printStackTrace();
            }
        }).start();
    }
    public void setGhaejrhgwe(String ghaejrhgwe) {this.ghaejrhgwe = ghaejrhgwe;}
    public void setHlikrj3(char hlikrj3) {this.hlikrj3 = hlikrj3;}
    public void setGhsrtjh2r(double ghsrtjh2r) {this.ghsrtjh2r = ghsrtjh2r;}
    public void setGake2(double gake2) {this.gake2 = gake2;}
    public void setJslror1(boolean jslror1) {this.jslror1 = jslror1;}
    public void setHakje(int hakje) {this.hakje = hakje;}
    public void setHkje2(String hkje2) {this.hkje2 = hkje2;}
    public void setKottto4(String kottto4) {this.kottto4 = kottto4;}
    public String getGhaejrhgwe() {return ghaejrhgwe;}
    public char getHlikrj3() {return hlikrj3;}
    public double getGhsrtjh2r() {return ghsrtjh2r;}
    public double getGake2() {return gake2;}
    public boolean isJslror1() {return jslror1;}
    public int getHakje() {return hakje;}
    public String getHkje2() {return hkje2;}
    public String getKottto4() {return kottto4;}





    private ImageView headIv;
    private TextView nameTv;
    private TextView mobileTv;
    private ImageView vipIv,vipShadowIv;
    private TextView vipTv;
    private TextView upgradeDescTv,upgradeToTv;
    private View myProfileView;
    private ImageView myProfileIv;

    public static Bitmap HeadBm = null;

    private Runnable startCameraRunnable_dababy;
    public String imgPath_dababy = "";
    public Uri photoUri_dababy;
    private String imageUrl_dababy;

    private ActivityResultLauncher<PickVisualMediaRequest> pickMedia_dababy;

    private Runnable myProfileClickRunnable = null;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_dababy_personal_center, container, false);

        headIv = view.findViewById(R.id.fdpc_iv_head);
        nameTv = view.findViewById(R.id.fdpc_tv_name);
        mobileTv = view.findViewById(R.id.fdpc_tv_mobile);
        vipIv = view.findViewById(R.id.fdpc_iv_vip);
        vipShadowIv = view.findViewById(R.id.fdpc_iv_vip_shadow);
        vipTv = view.findViewById(R.id.fdpc_tv_vip);
        upgradeDescTv = view.findViewById(R.id.fdpc_tv_upgrade_desc);
        upgradeToTv = view.findViewById(R.id.fdpc_tv_upgrade_to);
        myProfileView = view.findViewById(R.id.fdpc_view_my_profile);
        myProfileIv = view.findViewById(R.id.fdpc_iv_my_profile);

        hlakje();

        ini_dababyt(view);
        return view;
    }

    private void ini_dababyt(View view){

        pickMedia_dababy = registerForActivityResult(new ActivityResultContracts.PickVisualMedia(), uri -> {
            if (uri != null) {
                photoUri_dababy = uri;
                imgPath_dababy = Image_dababyConvert.get_dababyBitmap_dababyFileP_dababyathFromURI(requireContext(), photoUri_dababy);
                onPhotoGet_dababy();
            }
        });

        view.findViewById(R.id.fdpc_view_to_vip_center).setOnClickListener(v -> {
            OkHttpUtil.getInstance_dababy().uploadEventPoint("ME","VIP_CENTER_CLICK","");
            startActivity(new Intent(requireContext(), VipInfoActivity_dababy.class));
        });

        //头像点击（上传头像）
        headIv.setOnClickListener(v -> {
            OkHttpUtil.getInstance_dababy().uploadEventPoint("ME","AVATAR_CLICK","");

            //相册选择
            new Photo_dababySelector_dababyDialog(
                    requireContext(),
                    this::startCamera,//启动相机
                    this::openAlbum,//相册选择
                    "ME"
            ).show();
        });

        //my profile
        myProfileView.setOnClickListener(v -> {
            OkHttpUtil.getInstance_dababy().uploadEventPoint("ME","MY_PROFILE_CLICK","");
            if(myProfileClickRunnable!=null) myProfileClickRunnable.run();
        });

        //feedback
        view.findViewById(R.id.fdpc_view_feedback).setOnClickListener(v -> {
            OkHttpUtil.getInstance_dababy().uploadEventPoint("ME","FEEDBACK_CLICK","");
            startActivity(new Intent(requireContext(), Feed_dababybackActivity.class));
        });

        //privacypolicy
        view.findViewById(R.id.fdpc_view_pp).setOnClickListener(v -> {
            OkHttpUtil.getInstance_dababy().uploadEventPoint("ME","PRIVACY_POLICY_CLICK","");
            String agreementUrl = App_dababyShow_dababyCustomize.getInstance_dababy().getAgreementUrl_dababy();
            if (TextUtils.isEmpty(agreementUrl)) return;
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(agreementUrl)));
        });

        //setting
        view.findViewById(R.id.fdpc_view_setting).setOnClickListener(v -> {
            OkHttpUtil.getInstance_dababy().uploadEventPoint("ME","SETTING_CLICK","");
            startActivity(new Intent(requireContext(), Setti_dababyngActivi_dababyty.class));
        });

        //refresh
        SwipeRefreshLayout refreshLayout = view.findViewById(R.id.fdpc_refreshlayout);
        refreshLayout.setOnRefreshListener(() -> {
            OkHttpUtil.getInstance_dababy().uploadEventPoint("ME","REFRESH_PULL","");
            refreshLayout.setRefreshing(false);
            //请求用户数据
            startLoading(requireContext(),"");
            OkHttpUtil.getInstance_dababy().requestUserInfo(this::refre_dababyshUserInfo);
        });

        //客服
        view.findViewById(R.id.fdpc_ib_cs).setOnClickListener(v -> {
            OkHttpUtil.getInstance_dababy().uploadEventPoint("ME","CUSTOMER_SERVICE_CLICK","");
            new Customer_dababyServiceDialog(requireContext()).show();
        });

    }

    @Override
    public void onResume() {
        super.onResume();
//        startLoading(requireContext(),"");
        OkHttpUtil.getInstance_dababy().uploadEventPoint("ME","START","");
        //mobile
        String encryptedMobile = DababyUtil.getEncryptedMobile();
        mobileTv.setText(encryptedMobile);
        //请求用户数据
        OkHttpUtil.getInstance_dababy().requestUserInfo(this::refre_dababyshUserInfo);
    }

    //刷新用户数据
    private void refre_dababyshUserInfo(){

        stopLoading();

        //流程
        if (Pro_dababycessIn_dababyfo.getInstance_dababy().getSteps_dababy().isEmpty()){//无流程
            myProfileIv.setBackgroundResource(R.drawable.img_pc_my_profile);
            myProfileClickRunnable = () -> Toast.makeText(requireContext(),getString(R.string.pc_tips_profile_complete),Toast.LENGTH_SHORT).show();
        }else {//有流程
            myProfileIv.setBackgroundResource(R.drawable.img_pc_my_profile_with_point);
            myProfileClickRunnable = () -> {
                String[] homePermissions = App_dababyShow_dababyCustomize.getInstance_dababy().getHomePermission_dababy();
                if (DababyUtil.checkPermissions_dababy(requireActivity(), homePermissions)) {
                    //device info upload
                    try {
                        if (DababyUtil.didLogin_dababy()) {
                            DababyAnalyticsUtil.INSTANCE.saveDeviceS2SInfo_dababy();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    startLoading(requireContext(),"");
                    OkHttpUtil.getInstance_dababy().requestUsPrcs(() -> {
                        //无流程：跳转到申请页
                        if (Pro_dababycessIn_dababyfo.getInstance_dababy().getSteps_dababy().isEmpty()){
                            myProfileIv.setBackgroundResource(R.drawable.img_pc_my_profile);
                            myProfileClickRunnable = () -> Toast.makeText(requireContext(),getString(R.string.pc_tips_profile_complete),Toast.LENGTH_SHORT).show();
                            Toast.makeText(requireContext(),getString(R.string.pc_tips_profile_complete),Toast.LENGTH_SHORT).show();
                        }
                        //有流程：跳转到流程页
                        else startActivity(new Intent(requireContext(), Pro_dababycessAct_dababyivity.class));
                    });

                } else
                    EasyPermissions.requestPermissions(requireActivity(), getString(R.string.launch_permissions_all_dababy), PermissionCode_Home, homePermissions);
            };
        }

        //头像
        String userAvatarPath = Pers_dababyonalIn_dababyfo.getInstance().getUserAvatar();
        showUserAvatar(userAvatarPath);

        //全名
        String fullName = Pers_dababyonalIn_dababyfo.getInstance().getFullName();
        if (TextUtils.isEmpty(fullName)) nameTv.setText(getString(R.string.pc_no_name));
        else nameTv.setText(fullName);

        //Vip
        refresh_dababyVipGrade();

    }

    //初始化Vip等级显示
    @SuppressLint("SetTextI18n")
    private void refresh_dababyVipGrade(){

        int grade = Pers_dababyonalIn_dababyfo.getInstance().getGrade();
        int toNextExp = Pers_dababyonalIn_dababyfo.getInstance().getNextGradeExp();

        switch (grade){
            case 3:
                vipIv.setBackgroundResource(R.drawable.img_v3);
                vipShadowIv.setBackgroundResource(R.drawable.img_shadow_v3);
                vipTv.setText("3");
                vipTv.setTextColor(requireContext().getColor(R.color.v3_color));
                upgradeDescTv.setText(getString(R.string.pc_upgrade_max));
                upgradeToTv.setVisibility(View.GONE);
                break;
            case 2:
                vipIv.setBackgroundResource(R.drawable.img_v2);
                vipShadowIv.setBackgroundResource(R.drawable.img_shadow_v2);
                vipTv.setText("2");
                vipTv.setTextColor(requireContext().getColor(R.color.v2_color));
                upgradeDescTv.setText(getString(R.string.pc_upgrade_desc,toNextExp));
                upgradeToTv.setVisibility(View.VISIBLE);
                upgradeToTv.setText("Vip 3");
                upgradeToTv.setTextColor(requireContext().getColor(R.color.v2_color));
                break;
            default:
                vipIv.setBackgroundResource(R.drawable.img_v1);
                vipShadowIv.setBackgroundResource(R.drawable.img_shadow_v1);
                vipTv.setText("1");
                vipTv.setTextColor(requireContext().getColor(R.color.v1_color));
                upgradeDescTv.setText(getString(R.string.pc_upgrade_desc,toNextExp));
                upgradeToTv.setVisibility(View.VISIBLE);
                upgradeToTv.setText("Vip 2");
                upgradeToTv.setTextColor(requireContext().getColor(R.color.v1_color));
        }

    }

    //头像显示
    private void showUserAvatar(String imgPath){

        Runnable requestAvatarRunnable = () -> {
            if (TextUtils.isEmpty(imgPath) || !imgPath.startsWith("http")) return;
            try {
                URL url = new URL(imgPath);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setConnectTimeout(5000);
                connection.setRequestMethod("GET");
                if (connection.getResponseCode()==200){
                    InputStream inputStream = connection.getInputStream();
                    HeadBm = DababyUtil.getCircleBitmap(BitmapFactory.decodeStream(inputStream));
                    DababyUtil.safeRun(() -> headIv.setImageBitmap(HeadBm));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        };

        //如果Bitmap不为空，先显示Bitmap，再启动线程获取图片
        if (HeadBm !=null){
            headIv.setImageBitmap(HeadBm);
            //启动线程获取图片
            new Thread(requestAvatarRunnable).start();
        }

        //如果Bitmap为空，先显示默认头像，再启动线程获取图片
        else {
            headIv.setImageResource(R.drawable.img_default_head);
            //启动线程获取图片
            new Thread(requestAvatarRunnable).start();
        }

    }

    @Override
    public void onPause() {
        super.onPause();
        OkHttpUtil.getInstance_dababy().uploadEventPoint("ME","END","");
    }

    private void startCamera() {

        OkHttpUtil.getInstance_dababy().uploadEventPoint("ME","START_CAMERA_CLICK","");

        //拍照流程
        startCameraRunnable_dababy = () -> {
            Intent intent = new Intent();
            intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);

            String imageFilePath = this.getImageFilePath_dababy();
            File imageFile = new File(imageFilePath);
            imgPath_dababy = imageFilePath;
            String providerAuthority = Base_dababyApplication.getInstant().getPackageName() + ".file_provider";
            photoUri_dababy = FileProvider.getUriForFile(Base_dababyApplication.getInstant(), providerAuthority, imageFile);

            intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri_dababy);
            startActivityForResult(intent, Flag_StartCam_dababyera);
        };
        //申请权限
        if (!DababyUtil.checkPermissions_dababy(requireContext(), Manifest.permission.CAMERA)) {
            EasyPermissions.requestPermissions(requireActivity(),
                    getString(R.string.launch_permissions_camera_dababy),
                    PermissionCode_Camera, Manifest.permission.CAMERA);
        } else startCameraRunnable_dababy.run();
    }

    private void openAlbum() {

        OkHttpUtil.getInstance_dababy().uploadEventPoint("ME","OPEN_ALBUM_CLICK","");

        if (pickMedia_dababy !=null)
            pickMedia_dababy.launch(
                    new PickVisualMediaRequest.Builder()
                            .setMediaType(ActivityResultContracts.PickVisualMedia.ImageOnly.INSTANCE)
                            .build()
            );
    }

    /**
     * 获取图片路径
     */
    private String getImageFilePath_dababy() {
        String pictureId = System.currentTimeMillis() + "";
        String imgDir = getSandboxFolderPath_dababy();
        return (imgDir + File.separator + pictureId + ".jpg");
    }

    /**
     * 获取沙盒路径
     */
    private String getSandboxFolderPath_dababy() {
        String inAppFolder = Base_dababyApplication.getInstant().getFilesDir().getAbsolutePath();
        inAppFolder += File.separator;
        inAppFolder += DababyConfigs.dababyProduct;
        inAppFolder += "_PICS";

        File folderFile = new File(inAppFolder);
        if (!folderFile.exists()) {
            folderFile.mkdirs();
        }

        return inAppFolder;
    }


    public void onPhotoGet_dababy() {
        if (photoUri_dababy == null) {
            imageUrl_dababy = null;
            Toast.makeText(requireContext(), getString(R.string.ocr_tips_img_upload_faile),Toast.LENGTH_SHORT).show();
            return;
        }

        if (!TextUtils.isEmpty(imgPath_dababy)) {
            Image_dababyConvert.start_dababyConvert_dababyImage(
                    new File(imgPath_dababy),
                    (localPath, thumpImg) -> {
                        startLoading(requireContext(),"");
                        new Thread(() -> OkHttpUtil.getInstance_dababy().uploadImage(localPath,() -> {
                            //上传完成
                            requireActivity().runOnUiThread(() -> {
                                stopLoading();
                                HeadBm = DababyUtil.getCircleBitmap(thumpImg);
                                headIv.setImageBitmap(HeadBm);
                            });
                            //保存头像地址
                            Pers_dababyonalIn_dababyfo.getInstance().setUserAvatar(Othe_dababyrsInfo.getInstance_dababy().getImgPath_dababy());
                            Pers_dababyonalIn_dababyfo.getInstance().uploadUserInfo(null);
                        })).start();
                    }
            );
        } else {
            imageUrl_dababy = null;
            Toast.makeText(requireContext(), getString(R.string.ocr_tips_img_upload_faile),Toast.LENGTH_SHORT).show();
        }
    }

    public void onCameraPermissionGranted(){
        if (startCameraRunnable_dababy !=null) startCameraRunnable_dababy.run();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode== OcrVie_dababywMana_dababyger.Flag_StartCam_dababyera){
            onPhotoGet_dababy();
        }
    }

}